package com.online.web.shiro.action.shiro;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.online.web.shiro.biz.user.PermissionBiz;
import com.online.web.shiro.model.user.PermissionInfo;
import com.online.web.shiro.model.user.UserInfo;
import com.online.web.shiro.util.web.ActionUtil;

/**
 * 登陆
 * 
 * @author tongyufu
 *
 */
@Controller
public class PassportAction {

    Logger                log = LogManager.getLogger();
    @Autowired
    private PermissionBiz permissionBiz;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginView() {
        return "login.jsp";
    }

    /**
     * 用户登录失败
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginFailure(HttpServletRequest request, UserInfo userInfo, Model model) {
        String error = null;
        System.out.println("====登录====" + userInfo);
        try {
            //            if (!CaptchaImageCreateAction.validCaptcha(request, userInfo.getCaptcha())) {
            //                throw new AuthenticationException("验证码错误");
            //            }
            UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(),
                userInfo.getPassword());
            SecurityUtils.getSubject().login(token);
            userInfo = ActionUtil.getUser();
            List<PermissionInfo> permissions = permissionBiz.queryByUserId(userInfo.getId());
            request.getSession().setAttribute("_menu", permissions);
        } catch (UnknownAccountException e) {
            error = "用户名或密码错误";
        } catch (IncorrectCredentialsException e) {
            error = "用户名或密码错误";
        } catch (AuthenticationException e) {
            error = e.getMessage();
            log.error("", e);
        }
        if (StringUtils.isNotBlank(error)) {
            model.addAttribute("error", error);
            return "login.jsp";
        }
        return "redirect:/";
    }

    /**退出登录*/
    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "login.jsp";
    }

    @RequestMapping("/rememberMe")
    public String rememberMe() {
        return "rememberMe.jsp";
    }

    /**
     * 权限认证失败
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
        String xrequest = request.getHeader("x-requested-with");
        //ajax请求
        if ("XMLHttpRequest".equalsIgnoreCase(xrequest)) {
            response.setHeader("sessionstatus", "authorizationFailure");
            return null;
        } else {
            request.setAttribute("error", "没有对应的操作权限");
        }
        return "unauthorized.jsp";
    }
}
